package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.jws.Oneway;
import java.util.Date;


@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {


    //TODO 远程调用延迟队列接口
    @Autowired
    private IScheduleClient iScheduleClient;

    //审核文章
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间，可以作为任务的执行时间
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中__________________begin");
        //初始化
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        //TODO feign远程调用
        log.error("1.当前时间{}任务发布时间{}",System.currentTimeMillis(),task.getExecuteTime());
        iScheduleClient.addTask(task);

        log.info("添加任务到延迟服务中__________________end");

    }

    /**
     * 消费任务 审核文章
     */
    @Scheduled(fixedDelay = 1000)   //每一秒钟拉取一次 进行审核
    @Override
    public void scanNewsByTask() {
        //TODO feign远程调用
        ResponseResult responseResult = iScheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode().equals(200) && responseResult.getData() != null) {

            String s = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(s, Task.class);

            //反序列化
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            //消费任务 文章审核
            log.info("定时消费任务成功");
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());

        }
    }
}
